package com.x.rocketmq;

import com.alibaba.fastjson2.JSON;
import com.x.rocketmq.exception.RMQClientException;
import java.util.Map;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xjk
 * @date 2025-07-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RmqProducerService {


  @Autowired
  RocketMQProducerServer rocketMQProducerServer;

  public void sendMsgToMq(String topic, String tag, Object obj){
    String s = JSON.toJSONString(obj);
    sendToMq(topic, tag, s);
  }

  private void sendToMq(String topic, String tag, String body) {

    RocketMqMessageCommand command = new RocketMqMessageCommand();
    command.setMsgId(UUID.randomUUID().toString());
    command.setMsgBodySend(true);
    command.setTopic(topic);
    command.setTag(tag);
    command.setMsgType(tag);
    command.setMsgBody(body);

    Map<String, String> map = rocketMQProducerServer.sendDataMsgConcurrently(topic, tag, command);
    String code = map.get("code");
    if (!"0000".equals(code)) {
      String msg = "无法将消息发送到 RMQ " + map.get("msg");
      log.warn(msg);
      throw new RMQClientException(code, msg);
    }

  }


}
